<template>
    <div class="yuan-container container">
        <a-card  title="原药材库存表">
            <div class="filter-list" style="display: flex;justify-content: space-between">
                <div style="display: flex; align-items: center;">
                    <a-input-search
                        v-model="searchKeyword"
                        placeholder="请输入关键字搜索"
                        style="width: 250px; margin-right: 15px;"
                        @search="handleSearch"
                        allowClear
                    />
                    <a-range-picker
                        v-model="dateRange"
                        :locale="locale"
                        style="width: 280px; margin-right: 15px;"
                        @change="handleDateRangeChange"
                        format="YYYY-MM-DD"
                        valueFormat="YYYY-MM-DD"
                    />
                    <a-button type="primary" @click="handleSearch">搜索</a-button>
                    <a-tag style="margin-left: 10px;font-size: 18px;">数量总汇：{{ totalStock }}</a-tag>
                </div>
                <div>
                    <a-button style="margin-right:10px;z-index: 100;margin-bottom: 10px" type="primary" @click="add">新增</a-button>
                <a-button type="primary" @click="downloadTemplate">下载导入模板</a-button>
                <a-upload name="file" :multiple="false" :before-upload="beforeUpload" :showUploadList="false">
                    <a-button type="primary" style="margin-left: 5px;margin-right: 5px">导入</a-button>
                </a-upload>
                <a-button type="primary" @click="exportData">导出</a-button>
                </div>
            </div>

            <a-table
                :scroll="{ x: 7500 }"
                :loading="tableOption.loading"
                bordered
                :rowKey="item=>item.id"
                :data-source="tableOption.dataSource"
                :columns="tableOption.tableColumns"
                :pagination="tableOption.pagination">
            </a-table>
        </a-card>
        <!-- 弹窗表单 -->
        <addOrEdit :formData="formData" :visible="formShow" :editId="formEditId" @closeModal="formClose"></addOrEdit>
        <outStourage :operateType="operateType" :editId="formEditId" :visible="outStorageShow" :formData="currentRecord" @closeModal="outStorageClose"></outStourage>
        <Recheck :editId="formEditId" :visible="recheckShow" :formData="currentRecord" @closeModal="recheckClose"></Recheck>
    </div>
</template>
<script lang="ts">
import {Vue, Component} from 'vue-property-decorator';
import AddOrEdit from "@/views/reportMgt/rawMaterialInventory/components/addOrEdit.vue";
import OutStourage from "@/views/reportMgt/rawMaterialInventory/components/outStourage.vue";
import Recheck from "@/views/reportMgt/rawMaterialInventory/components/recheck.vue";
import {h} from "vue";
import nextApi from "@/api/nextApi";
import {downLoadFile} from "@/utils";
import locale from "ant-design-vue/lib/date-picker/locale/zh_CN";
@Component({
    components: {AddOrEdit, OutStourage, Recheck}
})
export default class  extends Vue {
    locale: any = locale;
    //表格配置
    tableOption: any = {
        loading:false,
        tableColumns: [
            {
                title:'基础信息',
                align:"center",
                className: 'basic-info-header',
                children:[
                    {
                        title:'品名',
                        key: "name",
                        align: "center",
                        dataIndex: "name",
                    },
                    {
                        title:'件数',
                        key: "num",
                        dataIndex: "num",
                        align: "center",
                    },
                    {
                        title:'件数结存',
                        key: "numBalance",
                        dataIndex: "numBalance",
                        align: "center",
                    },
                    {
                        title:'进厂日期',
                        key: "inDate",
                        dataIndex: "inDate",
                        align: "center",
                    },
                    {
                        title:'进厂编号',
                        key: "inNo",
                        dataIndex: "inNo",
                        align: "center",
                    },
                    {
                        title:'标准号',
                        key: "standardNumber",
                        dataIndex: "standardNumber",
                        align: 'center'
                    },
                    {
                        title:'流水号',
                        key: "serialNum",
                        dataIndex: "serialNum",
                        align: 'center'
                    },
                    {
                        title:'GMP编号',
                        key: "gmpNo",
                        dataIndex: "gmpNo",
                        align: 'center'
                    },
                    {
                        title:'数量结存',
                        key: "quantityStorage",
                        dataIndex: "quantityStorage",
                        align: 'center'
                    },
                    {
                        title:'存放类别',
                        key: "depositType",
                        dataIndex: "depositType",
                        align: 'center'
                    },
                    {
                        title:'是否超过半年',
                        key: "overHalfYear",
                        dataIndex: "overHalfYear",
                        align: 'center'
                    },
                    {
                        title:'有效期',
                        key: "validityDate",
                        dataIndex: "validityDate",
                        align: 'center'
                    },
                    {
                        title:'复验期',
                        key: "recheckDate",
                        dataIndex: "recheckDate",
                        align: 'center'
                    },
                    {
                        title:'来货采收日期',
                        key: "reapDate",
                        dataIndex: "reapDate",
                        align: 'center'
                    },
                    {
                        title:'备注',
                        key: "basicRemark",
                        dataIndex: "basicRemark",
                        align: 'center'
                    },
                    {
                        title:'部位类别',
                        key: "partType",
                        dataIndex: "partType",
                        align: 'center'
                    },
                    {
                        title:'YC',
                        key: "yc",
                        dataIndex: "yc",
                        align: 'center'
                    },
                    {
                        title:'水分',
                        key: "water",
                        dataIndex: "water",
                        align: 'center'
                    },
                    {
                        title:'初检数量',
                        key: "firstCheckNum",
                        dataIndex: "firstCheckNum",
                        align: 'center'
                    },
                    {
                        title:'毛重',
                        key: "mWeight",
                        dataIndex: "mWeight",
                        align: 'center'
                    },
                    {
                        title:'皮重',
                        key: "pWeight",
                        dataIndex: "pWeight",
                        align: 'center'
                    },
                    {
                        title:'初检扣杂',
                        key: "firstCheckSub",
                        dataIndex: "firstCheckSub",
                        align: 'center'
                    },
                    {
                        title:'GMP数量',
                        key: "gmpNum",
                        dataIndex: "gmpNum",
                        align: 'center'
                    },
                    {
                        title:'未折扣数量',
                        key: "notDiscountNum",
                        dataIndex: "notDiscountNum",
                        align: 'center'
                    },
                    {
                        title:'GMP数量和定包数量差异',
                        key: "gmpNumDiff",
                        dataIndex: "gmpNumDiff",
                        align: 'center'
                    },
                ]
            },
            {
                title:'检验信息',
                align:"center",
                className: 'check-info-header',
                children:[
                    {
                        title:'状态',
                        key: "state",
                        dataIndex: "state",
                        align: 'center',
                        customRender:(text:string,record:any,index:number)=>{
                            let arr = record.medicinalCheckRecordList.map(item=>{
                                return item.checkResult
                            })
                            return arr.length ? arr.join('、'):arr
                        }
                    },
                    {
                        title:'检验结果/其他',
                        key: "checkOther",
                        dataIndex: "checkOther",
                        align: 'center'
                    },
                    {
                        title:'检验结果/水分',
                        key: "checkWater",
                        dataIndex: "checkWater",
                        align: 'center'
                    },
                    {
                        title:'报告日期',
                        key: "reportDate",
                        dataIndex: "reportDate",
                        align: 'center'
                    },
                    {
                        title:'报告编号',
                        key: "reportNo",
                        dataIndex: "reportNo",
                        align: 'center'
                    },
                    {
                        title:'药典取样时间',
                        key: "drugTakeDate",
                        dataIndex: "drugTakeDate",
                        align: 'center'
                    },
                    {
                        title:'药典取样量',
                        key: "drugTakeNum",
                        dataIndex: "drugTakeNum",
                        align: 'center'
                    },
                    {
                        title:'药典放行时间',
                        key: "drugReleaseDate",
                        dataIndex: "drugReleaseDate",
                        align: 'center'
                    },
                    {
                        title:'国标取样时间',
                        key: "gbTakeDate",
                        dataIndex: "gbTakeDate",
                        align: 'center'
                    },
                    {
                        title:'国标取样量',
                        key: "gbTakeNum",
                        dataIndex: "gbTakeNum",
                        align: 'center'
                    },
                    {
                        title:'国标放行时间',
                        key: "gbReleaseDate",
                        dataIndex: "gbReleaseDate",
                        align: 'center'
                    },
                    {
                        title:'省标取样时间',
                        key: "sbTakeDate",
                        dataIndex: "sbTakeDate",
                        align: 'center'
                    },
                    {
                        title:'省标取样量',
                        key: "sbTakeNum",
                        dataIndex: "sbTakeNum",
                        align: 'center'
                    },
                    {
                        title:'省标放行日期',
                        key: "sbReleaseDate",
                        dataIndex: "sbReleaseDate",
                        align: 'center'
                    },
                    {
                        title:'黄曲霉素取样日期',
                        key: "aflatoxinTakeDate",
                        dataIndex: "aflatoxinTakeDate",
                        align: 'center'
                    },
                    {
                        title:'特殊类别请验日期',
                        key: "specialCheckDate",
                        dataIndex: "specialCheckDate",
                        align: 'center'
                    },
                ]
            },
            {
                title:'入库信息',
                align:"center",
                className: 'in-storage-info-header',
                children:[
                    {
                        title:'存放地点',
                        key: "putLocation",
                        dataIndex: "putLocation",
                        align: 'center'
                    },
                    {
                        title:'供货商',
                        key: "supply",
                        dataIndex: "supply",
                        align: 'center'
                    },
                    {
                        title:'规格',
                        key: "spec",
                        dataIndex: "spec",
                        align: 'center'
                    },
                    {
                        title:'备注1',
                        key: "inRemark",
                        dataIndex: "inRemark",
                        align: 'center'
                    },
                    {
                        title:'产地',
                        key: "origin",
                        dataIndex: "origin",
                        align: 'center'
                    },
                    {
                        title:'入库数量（kg）',
                        key: "inNumber",
                        dataIndex: "inNumber",
                        align: 'center'
                    },
                    {
                        title:'入库件数（件）',
                        key: "inNum",
                        dataIndex: "inNum",
                        align: 'center'
                    },
                    {
                        title:'入库日期',
                        key: "inDate2",
                        dataIndex: "inDate2",
                        align: 'center'
                    },
                ]
            },
            {
                title:'出库信息',
                align:"center",
                className: 'out-storage-info-header',
                children:[
                    {
                        title:'出库数量',
                        key: "outNumber",
                        dataIndex: "outNumber",
                        align: 'center'
                    },
                    {
                        title:'出库件数',
                        key: "outNum",
                        dataIndex: "outNum",
                        align: 'center'
                    },
                    {
                        title:'出库时间',
                        key: "outDate",
                        dataIndex: "outDate",
                        align: 'center'
                    },
                    {
                        title:'盘盈',
                        key: "outPy",
                        dataIndex: "outPy",
                        align: 'center'
                    },
                    {
                        title:'报损',
                        key: "outLoss",
                        dataIndex: "outLoss",
                        align: 'center'
                    },
                ]
            },
            {
                title:'复检信息',
                align:"center",
                className:'recheck-info-header',
                children:[
                    {
                        title:'复检状态',
                        key: "recheckState",
                        dataIndex: "recheckState",
                        align: 'center'
                    },
                    {
                        title:'复检结果',
                        key: "recheckResult",
                        dataIndex: "recheckResult",
                        align: 'center'
                    },
                    {
                        title:'药典复检取样时间',
                        key: "recheckTakeDate",
                        dataIndex: "recheckTakeDate",
                        align: 'center'
                    },
                    {
                        title:'药典复检取样量',
                        key: "recheckTakeNum",
                        dataIndex: "recheckTakeNum",
                        align: 'center'
                    },
                    {
                        title:'药典复检放行时间',
                        key: "recheckReleaseDate",
                        dataIndex: "recheckReleaseDate",
                        align: 'center'
                    },
                    {
                        title:'国标复检取样时间',
                        key: "recheckBgTakeDate",
                        dataIndex: "recheckBgTakeDate",
                        align: 'center'
                    },
                    {
                        title:'省标复检取样时间',
                        key: "recheckSbTakeDate",
                        dataIndex: "recheckSbTakeDate",
                        align: 'center'
                    },
                    {
                        title:'国标复检取样量',
                        key: "recheckBgTakeNum",
                        dataIndex: "recheckBgTakeNum",
                        align: 'center'
                    },
                    {
                        title:'省标复检取样量',
                        key: "recheckSbTakeNum",
                        dataIndex: "recheckSbTakeNum",
                        align: 'center'
                    },
                    {
                        title:'国标复检放行时间',
                        key: "recheckBgReleaseDate",
                        dataIndex: "recheckBgReleaseDate",
                        align: 'center'
                    },
                    {
                        title:'省标复检放行时间',
                        key: "recheckSbReleaseDate",
                        dataIndex: "recheckSbReleaseDate",
                        align: 'center'
                    },
                ]
            },
            {
                title:'操作',
                dataIndex: 'operation',
                align: 'center',
                fixed: 'right',
                customRender: (text: any, record: any) => {
                    return this.$createElement('div', {}, [
                        this.$createElement('a-button', {
                            props: { type: 'primary' },
                            style: { 'margin-right': '8px',display:record.tempState === '1' ? 'inline-block':'none' },
                            on: { click: () => this.edit(record) }
                        }, '继续填写'),
                        this.$createElement('a-button', {
                            props: { type: 'primary' },
                            style: { 'margin-right': '8px' },
                            on: { click: () => this.outStorage(record,1) }
                        }, '出库'),
                        this.$createElement('a-button', {
                            props: { type: 'primary' },
                            style: { 'margin-right': '8px' },
                            on: { click: () => this.outStorage(record,2) }
                        }, '退库'),
                        this.$createElement('a-button', {
                            props: { type: 'primary' },
                            on: { click: () => this.recheck(record) }
                        }, '复检')
                    ]);
                }
            }
        ],
        dataSource: [],
        pagination: {
            pageSize: 10,
            current: 1,
            total: 0,
            showTotal: (total: number) => `共${total}条`,
            onChange: this.pageChange,
        }
    }
    totalStock:number = 0
    pageChange(page: number, pageSize: number) {
        this.tableOption.pagination.current = page
        this.getTableData()
    }
    formShow = false
    outStorageShow = false
    currentRecord: any = {}
    add(){
        this.formShow = true
    }
    del(record: any){
    }
    formEditId = ''
    formData:any = {}
    edit(record:any){
        this.formShow = true
        this.formData = record
        this.formEditId = record.id
    }
    async updateByTable(record:any){
        try {
            this.tableOption.loading = true
            const result = await nextApi.productStorageUpdate(record)
            this.$message.success(result.msg)
            await this.getTableData()
        }finally {
            this.tableOption.loading = false
            await this.getTableData()
        }
    }
    formClose(){
        this.formShow = false
        this.formEditId = ''
        this.getTableData()
    }
    async getTableData(){
        try {
            this.tableOption.loading = true
            let params: any = {
                pageSize: this.tableOption.pagination.pageSize,
                page: this.tableOption.pagination.current,
            }
            if (this.searchKeyword) {
                params.name = this.searchKeyword;
            }
            if (this.dateRange && this.dateRange.length === 2) {
                params.inDate2Start = this.dateRange[0];
                params.inDate2End = this.dateRange[1];
            }
            const res = await nextApi.getRawMaterialTableData(params)
            this.tableOption.dataSource = res.data?.records || []
            this.tableOption.pagination.total = res.data?.total || 0
            this.totalStock = res.data?.totalStock || 0
            console.log(this.tableOption.dataSource)
        }finally {
            this.tableOption.loading = false
        }
    }
    beforeMount() {
        this.tableOption.tableColumns.forEach((item,i)=>{
            item.width = 150
            if(item.title == '操作')item.width = 360
            if(item.title == '操作')item.fixed = 'right'
        })
    }
    mounted() {
        this.getTableData()
    }
    downloadTemplate(){
        this.tableOption.loading = true
        nextApi.exportRawTemplate((res: any) => {
            const blob = new Blob([res.data], {
                type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                // type: "application/vnd.ms-excel",
            });
            downLoadFile(blob,"原药材库存表导入模板");
            this.tableOption.loading = false;
        });
    }
    beforeUpload(file: any) {
        let formData = new FormData();
        formData.append("file", file);
        // formData.append("materialType", '中药材')
        this.uploadTemplate(formData);
        return false;
    }
    async uploadTemplate(formData: any) {
        this.tableOption.loading = true;
        try {
            const res = await nextApi.importUnProductStorage(formData);
            this.$message.success(res.msg);
            await this.getTableData()
        } finally {
            this.tableOption.loading = false;
        }
    }
    operateType:number = 1
    outStorage(record: any,operateType:number) {
        this.currentRecord = record
        this.outStorageShow = true
        this.formEditId = record.id
        this.operateType = operateType
    }
    outStorageClose() {
        this.outStorageShow = false
        this.currentRecord = {}
        this.getTableData()
    }
    recheckShow = false
    recheck(record: any) {
        this.currentRecord = record
        this.recheckShow = true
        this.formEditId = record.id
    }
    recheckClose() {
        this.recheckShow = false
        this.currentRecord = {}
        this.getTableData()
    }
    searchKeyword = ''
    dateRange = []
    handleSearch() {
        // 实现搜索逻辑
        this.getTableData()
    }
    handleDateRangeChange(dates: any, dateStrings: any) {
        // 实现日期范围变化逻辑
        this.getTableData()
    }
    async exportData() {
        let tempState:any = null 
        let cofig:any = {
            closable:true,
            title: '是否导出全部(包含暂存)数据？',
            okText: "导出全部（包含暂存）",
            cancelText: "导出非暂存数据",
            cancelButtonProps:{
                on:{
                    click:()=>{
                        tempState = 2
                        exportData()
                    }
                }
            },
            onOk: async () => {
                tempState = 1
                exportData()
            },
        } 
        this.$confirm(cofig)

        let exportData =()=>{
            try {
                    this.tableOption.loading = true;
                    let params = {
                        tempState,
                        name:this.searchKeyword,
                        inDate2Start:this.dateRange[0],
                        inDate2End:this.dateRange[1],
                    }
                    nextApi.exportRawData(params,(res: any) => {
                        const blob = new Blob([res.data], {
                            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        });
                        downLoadFile(blob, '原药材库存表_' + new Date().toISOString().slice(0, 10));
                        this.tableOption.loading = false;
                    });
                } catch (error) {
                    this.$message.error('导出失败');
                    this.tableOption.loading = false;
                }
        }
    }
}
</script>
<style lang="scss">
.ant-table-thead > tr > th {
    &.basic-info-header {
        background-color: #f39d099c !important;
        font-size: 24px;
    }
    &.check-info-header {
        background-color: #87cfeb9c !important;
        font-size: 24px;
    }
    &.in-storage-info-header {
        background-color: #98fb98a1 !important;
        font-size: 24px;
    }
    &.out-storage-info-header {
        background-color: #add8e68f !important;
        font-size: 24px;
    }
    &.recheck-info-header{
        background-color: #ce30f594 !important;
        font-size: 24px;
    }
}

</style>
